package com.thank.concurrency.samples.commonUnsafe;

import com.thank.concurrency.annoations.NotThreadSafe;
import com.thank.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 显示JotaTime线程安全
 */
@ThreadSafe
@Slf4j
public class DateFormatExample2 {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    private static DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd");

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int x = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    parse(x);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception: ", e);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
    }

    // 在多线程环境下, 是会抛出异常的: java.lang.NumberFormatException: For input string: ""
    private static void parse(int x) {
        log.info("{}, {}", x, DateTime.parse("20180808", format).toDate());
    }
}
